package com.crane.oss.web.controller.sports;


import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.crane.common.core.dto.MultiResponse;
import com.crane.common.core.dto.Response;
import com.crane.common.core.dto.SingleResponse;
import com.crane.common.core.utils.CollectionUtil;
import com.crane.common.framework.utils.DateUtil;
import com.crane.oss.school.bean.resp.ClassesInfoResp;
import com.crane.oss.school.service.ClassesInfoService;
import com.crane.oss.sports.XunFeiAttendanceApiService;
import com.crane.oss.xunfei.req.QueryStudentAttendanceDetailReq;
import com.crane.oss.xunfei.req.QueryStudentAttendanceHistoryReq;
import com.crane.oss.xunfei.req.UpdateStudentAttendanceDetailReq;
import com.crane.oss.sports.bean.response.course.StudentAttendanceListResp;
import com.crane.oss.sports.bean.response.course.StudentAttendanceResp;
import com.crane.oss.sports.bean.response.studentattendance.AttendanceClassResp;
import com.crane.oss.sports.bean.resquest.QueryCourseAnalyzeReq;
import com.crane.oss.sports.bean.resquest.QuerySchoolClassReq;
import com.crane.oss.sports.bean.resquest.QueryStudentAttendanceReq;
import com.crane.oss.sports.bean.resquest.UpdateStudentAttendance;
import com.crane.oss.web.BaseBusinessController;
import com.crane.oss.xunfei.resp.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.util.Strings;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zx
 */
@Api(value = "StudentAttendanceController", tags = {"智慧体育-学生考勤"})
@RestController
@RequestMapping("/sports/student/attendance")
public class StudentAttendanceController  extends BaseBusinessController {

    @Resource
    ClassesInfoService classesInfoService;

    @Resource
    XunFeiAttendanceApiService xunFeiAttendanceApiService;

    @ApiOperation(value = "班级列表", notes = "班级列表")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "QuerySchoolClassReq")
    @PostMapping("/index")
    public SingleResponse<Map<String, List<AttendanceClassResp>>> classList(@RequestBody QuerySchoolClassReq request) {

        List<Long> classIds = null;
        if(CollectionUtil.isEmpty(request.getClassIds())){
            classIds=classesInfoService.queryClassesForSchoolId(request.getSchoolId()).stream().map(ClassesInfoResp::getClassId).collect(Collectors.toList());
        }else{
            classIds = request.getClassIds();
        }
        com.crane.oss.xunfei.req.QueryStudentAttendanceReq queryStudentAttendanceReq =new com.crane.oss.xunfei.req.QueryStudentAttendanceReq();
        queryStudentAttendanceReq.setTime(DateUtil.formatDateTime("yyyy年MM月",request.getTime()));
        queryStudentAttendanceReq.setClassIds(Strings.join(classIds,','));
        ApiListResponse<StudentClassAttendanceResp> response=xunFeiAttendanceApiService.getStudentAttendance(queryStudentAttendanceReq,getPartyId().toString(), null,getUserId().toString());
        if(null != response.getMsg() && response.getMsg().equals("success")){
            Map<String, List<AttendanceClassResp>> map=response.getData().stream().map(s ->{
                AttendanceClassResp a=new AttendanceClassResp();
                a.setClassName(s.getClassName());
                a.setDayTime(s.getDayTime());
                a.setClassTime(s.getClassTime());
                a.setAttendanceRate(s.getAttendanceRate());
                a.setAbnormal(s.getAbnormal());
                a.setCourseId(s.getCourseId());
                a.setWeek(DateUtil.getWeek(new Date(s.getDayTimeValue())));
                return a;
            }).collect(Collectors.groupingBy(AttendanceClassResp ::getDayTime));
            return SingleResponse.of(map);
        }
        return SingleResponse.of(null);
    }

    @ApiOperation(value = "学生考勤列表", notes = "学生考勤列表")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "QueryCourseAnalyzeReq")
    @PostMapping("/list")
    public MultiResponse<StudentAttendanceListResp> studentAttendance(@RequestBody QueryCourseAnalyzeReq request) {
        QueryStudentAttendanceDetailReq queryStudentAttendanceDetailReq=new QueryStudentAttendanceDetailReq();
        queryStudentAttendanceDetailReq.setCourseId(request.getCourseId());
        ApiListResponse<StudentAttendanceDetailResp> response=xunFeiAttendanceApiService.getStudentAttendanceDetail(queryStudentAttendanceDetailReq,getPartyId().toString(), null,getUserId().toString());
        if(null != response.getMsg() && response.getMsg().equals("success")){
            List<StudentAttendanceListResp> respList=response.getData().stream().map(s ->{
                StudentAttendanceListResp a=new StudentAttendanceListResp();
                a.setXsbh(s.getXsbh());
                a.setXsxm(s.getXsxm());
                a.setAttendanceFlag(s.getAttendanceFlag());
                a.setStudentId(s.getStudentId());
                return a;
            }).collect(Collectors.toList());
            return MultiResponse.ofWithoutTotal(respList);
        }
        return MultiResponse.ofWithoutTotal(new ArrayList<>());
    }

    @ApiOperation(value = "体育课堂-修改考勤", notes = "体育课堂-修改考勤")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "UpdateStudentAttendance")
    @PostMapping("/modify/attendance")
    public Response modifyAttendance(@RequestBody UpdateStudentAttendance request) {
        UpdateStudentAttendanceDetailReq updateStudentAttendance =new UpdateStudentAttendanceDetailReq();
        updateStudentAttendance.setCourseId(request.getCourseId());
        updateStudentAttendance.setStudentId(request.getList().stream().map(StudentAttendanceListResp::getStudentId).collect(Collectors.joining(",")));
        updateStudentAttendance.setAttendanceFlag(request.getList().stream().map(s -> String.valueOf(s.getAttendanceFlag())).collect(Collectors.joining(",")));
        ApiSingleResponse<String> response =xunFeiAttendanceApiService.updateStudentAttendance(updateStudentAttendance,getPartyId().toString(), null,getUserId().toString());
        if(null != response.getMsg() && response.getMsg().equals("success")){
            return Response.buildSuccess();
        }
        return Response.buildFailure("修改失败");
    }

    @ApiOperation(value = "个人考勤列表", notes = "个人考勤列表")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "QueryStudentAttendanceReq")
    @PostMapping("/list/one")
    public MultiResponse<StudentAttendanceResp> studentAttendance(@RequestBody QueryStudentAttendanceReq request) {
        QueryStudentAttendanceHistoryReq queryStudentAttendanceHistoryReq=new QueryStudentAttendanceHistoryReq();
        queryStudentAttendanceHistoryReq.setStudentId(request.getStudentId());
        queryStudentAttendanceHistoryReq.setTeachCycleId(request.getTeachCycleId());
        if(null != request.getBeginDate()){
            queryStudentAttendanceHistoryReq.setBeginTime(request.getBeginDate().getTime());
        }
        if(null != request.getEndDate()){
            queryStudentAttendanceHistoryReq.setEndTime(request.getEndDate().getTime());
        }
        queryStudentAttendanceHistoryReq.setPage(request.getPageNo());
        queryStudentAttendanceHistoryReq.setLimit(request.getPageSize());
        ApiListResponse<StudentAttendanceHistoryResp> response= xunFeiAttendanceApiService.getStudentAttendanceHistory(queryStudentAttendanceHistoryReq, getPartyId().toString(), null,getUserId().toString());
        if(null != response.getMsg() &&response.getMsg().equals("success")){
            List<StudentAttendanceResp> respList=response.getData().stream().map(s ->{
                StudentAttendanceResp a=new StudentAttendanceResp();
                a.setCourseName(s.getCourseName());
                a.setBeginTime(s.getBeginTimeValue());
                a.setEndTime(s.getEndTimeValue());
                a.setAttendanceFlag(s.getAttendanceFlag());
                a.setDayTime(s.getDayTimeValue());
                a.setTeacherName(s.getTeacherName());
                return  a;
            }).collect(Collectors.toList());
            return MultiResponse.of(respList,response.getTotal(),request);
        }
        return MultiResponse.of(new ArrayList<>(),0,request);
    }


    @ApiOperation(value = "个人考勤统计", notes = "个人考勤统计")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "QueryStudentAttendanceReq")
    @PostMapping("/statistic")
    public SingleResponse<StudentAttendanceStatisticResp> studentAttendanceStatistic(@RequestBody QueryStudentAttendanceReq request) {
        StudentAttendanceStatisticResp resp=new StudentAttendanceStatisticResp();
        QueryStudentAttendanceHistoryReq queryStudentAttendanceHistoryReq=new QueryStudentAttendanceHistoryReq();
        queryStudentAttendanceHistoryReq.setStudentId(request.getStudentId());
        queryStudentAttendanceHistoryReq.setTeachCycleId(request.getTeachCycleId());
        if(null != request.getBeginDate()){
            queryStudentAttendanceHistoryReq.setBeginTime(request.getBeginDate().getTime());
        }
        if(null != request.getEndDate()){
            queryStudentAttendanceHistoryReq.setEndTime(request.getEndDate().getTime());
        }
        ApiSingleResponse<StudentAttendanceStatisticResp> response= xunFeiAttendanceApiService.getStudentAttendanceStatistic(queryStudentAttendanceHistoryReq, getPartyId().toString(), null,getUserId().toString());
        if(null != response.getMsg() &&response.getMsg().equals("success")){
            resp=response.getData();
        }
        return SingleResponse.of(resp);
    }

}
